"use client"
import React, { useEffect, useRef, useState } from "react";
import { Button, Card, Drawer, message, Modal, Radio, Space, Tooltip } from "antd";
import HeaderClass from './index.module.css'
import {
    CheckOutlined,
    DownloadOutlined,
    DragOutlined, EyeOutlined, FileExcelOutlined, FileTextOutlined, FolderOpenOutlined,
    PictureOutlined, PlayCircleOutlined,
    PlusCircleOutlined,
    RedoOutlined,
    SaveOutlined,
    UndoOutlined, ZoomInOutlined, ZoomOutOutlined
} from "@ant-design/icons";

import { customTranslate } from "@/components/properties-panel-extension/modules/Translate";
// 高亮依赖
import hljs from 'highlight.js'
import { copyToClipboard } from "@/utils/clipboard";
import { List } from "postcss/lib/list";
import { globalMessage } from "@/utils/message";
import { initXml } from "@app/(view)/(layout)/system/flowable/editdefinition/component/initXml";

// 定义接口
interface ProcessError {
    id: string
    message: string
}

interface MyComponentProps {
    bpmnInstance: any;
    SaveXMl: (e: any) => void;
}
type ButtonType = 'link' | 'text' | 'primary' | 'default' | 'dashed';
const HeaderView: React.FC<MyComponentProps> = (props: any) => {
    const { bpmnInstance, SaveXMl } = props
    const { modeler, moddle, bpmnElement } = bpmnInstance;
    const [validateErrors, setValidateErrors] = useState<any[]>([]);
    const [validateVisible, setValidateVisible] = useState(false);
    // 预览功能
    const [openPreview, setOpenPreview] = useState<boolean>(false);
    const [previewContent, setPreviewContent] = useState<string>('');
    const [previewTitle, setPreviewTitle] = useState<string>();
    const [highlightedContent, setHighlightedContent] = useState('');
    let fileInputRef = useRef<HTMLInputElement>(null);
    useEffect(() => {
        const highlightedContentFun = () => {
            if (!previewContent) return ''
            const language = previewTitle?.toLowerCase().includes('json') ? 'json' : 'xml'
            return hljs.highlight(previewContent, { language }).value
        }
        setHighlightedContent(highlightedContentFun)
    }, [previewContent, previewTitle]);

    // 根据所需类型进行转码并返回下载地址
    function setEncoded(type: string, filename = "diagram", data: any) {
        const encodedData = encodeURIComponent(data);
        return {
            filename: `${filename}.${type}`,
            href: `data:application/${type === "svg" ? "text/xml" : "bpmn20-xml"
                };charset=UTF-8,${encodedData}`,
            data: data,
        };
    }

    // 保存并发布
    async function save() {
        const { xml } = await modeler.saveXML({ format: true });
        SaveXMl(xml)
    }



    // 下载流程文件
    async function downloadFile(type: string, name?: string) {
        try {
            // 按需要类型创建文件并下载
            if (type === "xml" || type === "bpmn") {
                const { err, xml } = await modeler.saveXML({ format: true });
                // 读取异常时抛出异常
                if (err) {
                    console.error(`[Process Designer Warn ]: ${err.message || err}`);
                }
                const { href, filename } = setEncoded("bpmn", name, xml);
                downloadFunc(href, filename);
            } else {
                const { err, svg } = await modeler.saveSVG();
                // 读取异常时抛出异常
                if (err) {
                    return console.error(err);
                }
                const { href, filename } = setEncoded("SVG", name, svg);
                downloadFunc(href, filename);
            }
        } catch (e: any) {
            console.error(`[Process Designer Warn ]: ${e.message || e}`);
        }

        // 文件下载方法
        function downloadFunc(href: any, filename: string) {
            if (href && filename) {
                const a: HTMLAnchorElement = document.createElement("a");
                a.download = filename; //指定下载的文件名
                a.href = href; //  URL对象
                a.click(); // 模拟点击
                URL.revokeObjectURL(a.href); // 释放URL 对象
            }
        }
    }

    //加载本地文件
    function importLocalFile() {
        const file = fileInputRef.current?.files?.[0] as File;
        const reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function () {
            const xmlStr = this.result;
            createNewDiagram(xmlStr).then(r => {

            });
        };
    }

    // 创建流程图
    async function createNewDiagram(xmlString: any) {
        try {
            const { warnings } = await modeler.importXML(xmlString);
            // if (warnings && warnings.length) {
            // warnings.forEach((warn) => console.warn(warn));
            // }
        } catch (e: any) {
            console.error(`[Process Designer Warn]: ${e.message || e}`);
        }
    }

    // 切换流程模拟器
    const toggleSimulation = () => {
        // simulationActive.value = !simulationActive.value
        const tokenSimulation = modeler.get('toggleMode')
        tokenSimulation.toggleMode()
    }
    // 流程校验
    const validateProcess = async () => {
        try {
            const linting = modeler.get('linting')
            const issues = await linting.lint()
            for (const key in issues) {
                if (Object.prototype.hasOwnProperty.call(issues, key)) {
                    issues[key].forEach((item: ProcessError) => {
                        setValidateErrors((oldValue) => [
                            ...oldValue,
                            {
                                id: item.id,
                                message: customTranslate(item.message),
                            }
                        ])
                    })
                }
            }
            setValidateVisible(true);
        } catch (err) {
            console.error(err)
            globalMessage().error('校验失败')
        }
    }
    // 预览功能XML
    const previewXML = async () => {
        try {
            const result = await modeler.saveXML({ format: true, preamble: true })
            setPreviewContent(result.xml || '')
            setPreviewTitle("预览 xml")
            setOpenPreview(true)
        } catch (err) {
            console.error(err)
            globalMessage().error('XML 生成失败')
        }
    }
    // 预览JSON
    const previewJSON = async () => {
        try {
            const result = await modeler.saveXML({ format: true })
            const jsonStr = await moddle.fromXML(result.xml!)
            const json = JSON.stringify(jsonStr, null, 2)
            setPreviewContent(json)
            setPreviewTitle('JSON 预览')
            setOpenPreview(true)
        } catch (err) {
            console.error(err)
            globalMessage().error('JSON 生成失败')
        }
    }
    // 复制内容
    const copyContent = async () => {
        try {
            await copyToClipboard(previewContent)
            globalMessage().success('复制成功')
        } catch (err) {
            console.error(err)
            globalMessage().error('复制失败')
        }
    }

    const iconBtnGroup: Array<{
        type: ButtonType;
        icon: React.ReactNode;
        title: string;
        onClick: () => void;
    }> = [
            {
                type: 'primary',
                icon: <SaveOutlined />,
                title: "保存并发布",
                onClick: () => save(),
            },
            {
                type: 'primary',
                icon: <FolderOpenOutlined />,
                title: "打开流程文件",
                onClick: () => fileInputRef && fileInputRef.current?.click(),
            },
            {
                type: 'primary',
                icon: <PlusCircleOutlined />,
                title: "创建新的流程图",
                onClick: () => {
                    console.log("bpmnElement", bpmnElement)
                    modeler.importXML(initXml)
                },
            },
            {
                type: 'primary',
                icon: <PictureOutlined />,
                title: "下载流程图",
                onClick: () => downloadFile("svg"),
            },
            {
                type: 'primary',
                icon: <DownloadOutlined />,
                title: "下载流程文件",
                onClick: () => downloadFile("bpmn"),
            }, {
                type: 'primary',
                icon: <EyeOutlined />,
                title: "预览XML",
                onClick: () => previewXML(),
            }, {
                type: 'primary',
                icon: <FileTextOutlined />,
                title: "预览JSON",
                onClick: () => previewJSON(),
            },
            {
                type: 'default',
                icon: <UndoOutlined />,
                title: "撤销",
                onClick: () => modeler.get("commandStack").undo(),
            },
            {
                type: 'default',
                icon: <RedoOutlined />,
                title: "恢复",
                onClick: () => modeler.get("commandStack").redo(),
            },
            {
                type: 'default',
                icon: <ZoomInOutlined />,
                title: "放大",
                onClick: () => modeler.get("zoomScroll").stepZoom(1),
            },
            {
                type: 'default',
                icon: <ZoomOutOutlined />,
                title: "缩小",
                onClick: () => modeler.get("zoomScroll").stepZoom(-1),
            },
            {
                type: 'default',
                icon: <DragOutlined />,
                title: "重置",
                onClick: () => modeler.get("canvas").zoom("fit-viewport", "auto"),
            },
            {
                type: 'default',
                icon: <PlayCircleOutlined />,
                title: "流程模拟",
                onClick: () => toggleSimulation(),
            }, {
                type: 'default',
                icon: <CheckOutlined />,
                title: "校验",
                onClick: () => validateProcess(),
            },
        ];
    return (<div >
        <Space.Compact className={HeaderClass.HeadClass}>
            {iconBtnGroup.map((item, index) => (
                <Tooltip
                    placement="bottom"
                    title={item.title}
                    key={index + 'iconBtnGroup'}
                    style={{ fontSize: 12 }}>
                    <Button size={"small"}  {...item} style={{ width: 44 }}></Button>
                </Tooltip>
            ))}
        </Space.Compact>

        <input
            type="file"
            ref={fileInputRef}
            style={{ display: "none" }}
            accept=".xml, .bpmn"
            onChange={importLocalFile}
        />
        {/*校验流程弹窗*/}
        <Modal
            forceRender
            open={validateVisible}
            title={"校验流程"}
            footer={null}
            onCancel={() => {
                setValidateVisible(false)
            }}>
            {validateErrors.length !== 0 && (
                <>{validateErrors.map((error, index) => (
                    <Card
                        key={error.id} // 使用 error.id 作为 key，确保唯一性
                        style={{ width: '100%' }}
                    >
                        <p>{'流程: ' + error.id}</p>
                        <p> {error.message}</p>
                    </Card>
                ))}</>
            )}
            {validateErrors.length == 0 && (<>
                <Card
                    title={"校验通过"}
                    style={{ width: '100%' }}
                >
                    <p>流程图符合规范要求</p>
                </Card>
            </>)}
        </Modal>
        {/*    预览XML*/}
        <Drawer
            title={previewTitle}
            size={"large"}
            onClose={() => {
                setOpenPreview(false)
            }}
            open={openPreview}
            extra={
                <Button type={"primary"} onClick={copyContent}>复制内容</Button>
            }>
            <pre className="preview-content" dangerouslySetInnerHTML={{ __html: highlightedContent }}></pre>
        </Drawer>
    </div>
    )
        ;
};

export default HeaderView;
